/**
 * 描述：表单数据源页面初始化
 * 作者：zhaohaibo
 * 日期：3/22/2019
 * 版本：0.0.1
 **/

(function(E, KIT, RES) {
  var __URL_ROOT = RES.URL_FORM_DESIGNER_ROOT,
    __URL_ADD = __URL_ROOT + "/addDataSource",
    __URL_UPDATE = __URL_ROOT + "/updateDataSource",
    __URL_TOGGLE_DISABLED = __URL_ROOT + "/toggleDisabledDataSource";

  var _clearTextBoxTag = function(suffix, check) {
      var __txt = rapid.ui("#txtName" + suffix).tag("id", null)
                       .tag("action", null).val(null)
                       .tip("在这里输入要添加的 " + (suffix === "Par" ? "数据源" : "数据项") + "名称...");

      $(__txt.submitButton()).children(".r-icon").removeClass("fa-check").addClass("fa-plus");

      rapid.ui("#btnCancel" + suffix).hide();

      if(check) {
        var __list_par = rapid("#lstPar").list();
        if(__list_par.count() === 0 || rapid.isEmpty(__list_par.selection())) {
          __txt = rapid.ui("#txtNameSub").disabled(true).tag("pid", null);
        } else {
          __txt = rapid.ui("#txtNameSub").disabled(false);
        }
      }

      return __txt;
    },

    _forUpdate = function(suffix) {
      var __selection = rapid("#lst" + suffix).list().selection();

      $(rapid.ui("#txtName" + suffix).tip("在这里输入要更换的名称...")
             .tag("id", __selection.value())
             .tag("action", "update").val(__selection.text()).focus()
             .submitButton())
        .children(".r-icon").removeClass("fa-plus").addClass("fa-check");

      rapid.ui("#btnCancel" + suffix).show();
    },

    _toggleDisabled = function(suffix, buttonText) {
      var __list = rapid("#lst" + suffix).list(),
        __text = __list.selection().text(),
        __id = __list.selection().value();

      rapid.confirm(
        "确定要" + buttonText + "“" + __text + "”" +
        (suffix === "Par" ? "数据源" : "数据项") + "吗？", function(e) {
          if(e) {
            rapid.post({
              url: __URL_TOGGLE_DISABLED,
              data: "id=" + __id + "&state=" + (buttonText == "禁用" ? "0" : "1"),
              responseMsg: false,
              complete: function() {
                if(suffix === "Par") {
                  _clearTextBoxTag("Sub", true);

                } else {
                  if(__id == rapid.ui("#txtNameSub").tag("id")) {
                    _clearTextBoxTag("Sub", false);
                  }
                }

                __list.reload();
              }
            });
          }
        });
    };

  var _initRootList = function() {
      rapid.ui("#txtNamePar").disabled(false);

      rapid("#lstPar").list({
        tag: {
          type: "parent"
        },
        dataSource: {
          textField: "name",
          valueField: "id",
          type: "post",
          url: RES.URL_FIND_FORM_DATASOURCE,
          data: "pid=0"
        },
        textFormatter: function(data) {
          if(data.state == 0) {
            return KIT.getDisabledText(data.name);
          }
          return data.name;
        }
      }).on("select", function(e) {
        _clearTextBoxTag("Par", false);
        _clearTextBoxTag("Sub", false).tag("pid", e.value());
        rapid.ui("#txtNameSub").disabled(false);

        rapid("#lstSub").list().load({
          data: "pid=" + e.value()
        });

      }).on("databound", function() {
        _clearTextBoxTag("Par", true);
      }).load();
    },

    _initSubList = function() {
      rapid("#lstSub").list({
        tag: {
          type: "sub"
        },
        dataSource: {
          textField: "name",
          valueField: "id",
          type: "post",
          url: RES.URL_FIND_FORM_DATASOURCE
        },
        textFormatter: function(data) {
          if(data.state == 0) {
            return KIT.getDisabledText(data.name);
          }
          return data.name;
        }
      }).on("select", function(e) {
        _clearTextBoxTag("Sub", false);

      }).on("databound", function() {
        _clearTextBoxTag("Sub", false);
      });
    },

    _initListItemMenu = function(suffix) {
      $("#lst" + suffix).on("contextmenu", ".r-item", function(e) {
        rapid.popupmenu({
          offset: e,
          actions: [{
            text: "编辑",
            icon: "fa-edit",
            handler: function() {
              _forUpdate(suffix);
            }
          }, {
            id: "toggleState",
            text: "禁用",
            icon: "fa-ban",
            handler: function(btn) {
              _toggleDisabled(suffix, btn.text());
            }
          }],
          onshow: function() {
            var __selection = rapid("#lst" + suffix).list().selection();

            if(__selection.data().state == 0) {
              this.action("toggleState").text("启用").icon("fa-check");
            }
          }
        });
      });
    },

    _initCancelUpdate = function(suffix) {
      rapid.ui("#btnCancel" + suffix).on("click", function() {
        _clearTextBoxTag(suffix, false);
      });
    },

    _initRootAddOrUpdate = function(suffix) {
      rapid.ui("#txtName" + suffix).on("submit", function() {
        var __name = this.val(),
          __last_value = this.lastValue();

        if(rapid.isEmpty(__name) || __name == __last_value) {
          return;
        }

        var __list = rapid("#lst" + suffix).list(),
          __txt = this,
          __action = rapid.nvl(__txt.tag("action"), "add"),
          __msg = "",
          __title = suffix === "Par" ? "数据源" : "数据项",
          __url;

        if(__action === "add") {
          __msg = "将创建" + __title + "“" + __name + "”，是否继续？";
          __url = __URL_ADD;

        } else {
          __msg = "将修改" + __title + "“" + __last_value + "”为“" + __name + "”，是否继续？";
          __url = __URL_UPDATE;
        }

        rapid.confirm(__msg, function(e) {
          if(e) {
            rapid.post({
              url: __url,
              responseMsg: false,
              data: "id=" + rapid.nvl(__txt.tag("id")) + "&pid=" + rapid.nvl(__txt.tag("pid")) +
                    "&name=" + rapid.encode(__name),
              success: function() {
                __list.reload();
                _clearTextBoxTag(suffix, suffix === "Par");
              },
              fail: function(e, msg) {
                rapid.fail(msg);
              },
              complete: function() {
                __txt.focus();
              }
            });

          } else {
            _clearTextBoxTag(suffix, suffix === "Par");
            __txt.focus();
          }
        });
      });
    };

  rapid.FormDataSource(function() {
    _initRootList();
    _initSubList();

    _initListItemMenu("Par");
    _initListItemMenu("Sub");

    _initRootAddOrUpdate("Par");
    _initRootAddOrUpdate("Sub");

    _initCancelUpdate("Par");
    _initCancelUpdate("Sub");
  }).init();

})(rapid.html.Element, rapid.kit, rapid.res);
 